import React, { useState, useEffect } from 'react';
import cn from 'classnames';
import moment from 'moment';
import s from './style.module.css';
import i from '../../index.module.css';
import BreadCrumb from '@/components/BreadCrumb';
import { deepClone } from '@/common/constant.js';
import {
  Table,
  Form,
  Input,
  Dialog,
  Button,
  Pagination,
  Message,
  Confirm,
  Dropdown,
  Menu,
  Tooltip,
  Select,
} from '@knownsec/react-component';

import {
  getRoleList as getRoleListApi,
  getPermissionList as getPermissionListApi,
  addRole as addRoleApi,
  delRole as delRoleApi,
  editRole as editRoleApi,
} from '../../../API/index';
export default function UserManage() {
  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 },
  };
  const [isModify, setIsModify] = useState(true);
  const [formAdd] = Form.useForm(); //新增角色
  const [formInfo] = Form.useForm(); //编辑信息
  const [count, setCount] = useState(0);
  const [tableData, setTableData] = useState([]);
  const [visibleAdd, setVisibleAdd] = useState(false); //添加角色
  const [visibleInfo, setVisibleInfo] = useState(0); //编辑信息
  const [isDown, setIsDown] = useState('');
  const [query, setQuery] = useState({
    page: 1,
    pageSize: 10,
  });
  const [loading, setLoading] = useState(false);
  const [roleOption, setRoleOption] = useState([]);
  const getPermissionList = async () => {
    try {
      const res = await getPermissionListApi();
      setRoleOption((roleOption) => {
        roleOption = res.data.data.map((item) => {
          return {
            label: item.permission,
            value: item.id,
          };
        });
        return roleOption;
      });
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(() => {
    getData();
    getPermissionList();
  }, [query]);
  function dealData(newItem) {
    const values = Object.keys(newItem).reduce((total, key) => {
      let value;
      if (newItem[key].selectedItem) {
        if (newItem[key].selectedItem.length > 0) {
          value = [...newItem[key].selectedItem.map((item) => item.value)];
        } else if (newItem[key].selectedItem.length === 0) {
          value = [];
        }
      } else if (Object.keys(newItem[key]).indexOf('value') > -1) {
        value = newItem[key].value;
      } else {
        value = newItem[key];
      }
      console.log(value);
      total[key] = value;
      return total;
    }, {});

    return values;
  }
  const onValues2 = (data) => {
    let values = dealData(data);
    formAdd.current.setFieldsValue(values);
  };
  const onValuesInfo = (newItem) => {
    const values = dealData(newItem);
    formInfo.current.setFieldsValue(values);
  };
  const getData = async () => {
    setLoading(true);
    try {
      const res = await getRoleListApi(query);
      console.log(res);
      setLoading(false);
      setTableData(res.data.data);
      setCount(res.data.count);
    } catch (err) {
      console.log(err);
    }
  };
  const [currentRoleId, setCurrentRoleId] = useState('');
  const editRoleInfo = async (item, isModify = true) => {
    formInfo.current.resetFields();
    setVisibleInfo(true);
    setCurrentRoleId(item.user_group_id);
    setIsModify(isModify);
    formInfo.current.setFieldsValue({
      group: item.group,
      desc: item.desc,
      modules: item.modules.map((item) => item.id),
    });
  };
  const submitInfo = (type) => {
    if (type === 'add') {
      formAdd.current.validateFields().then(async (res) => {
        const res_ = deepClone(res);
        res_.group = res_.group;
        try {
          const res = await addRoleApi(res_);
          if (res.status === 'success') {
            Message.show({
              pro: true,
              type: 'success',
              message: '操作成功',
              showClose: false,
            });
            setVisibleAdd(false);
            formAdd.current.resetFields();
            getData();
          }
        } catch (err) {
          console.log(err);
        }
      });
    } else if (type === 'info') {
      formInfo.current.validateFields().then(async (res) => {
        const res_ = deepClone(res);
        try {
          await editRoleApi({
            desc: res_.desc,
            modules: res_.modules,
            user_group_id: currentRoleId,
          });
          Message.show({
            pro: true,
            type: 'success',
            message: '操作成功',
            showClose: false,
          });
          setVisibleInfo(false);
          formInfo.current.resetFields();
          getData();
        } catch (err) {
          console.log(err);
        }
      });
    }
  };
  const delUserBtn = async (e) => {
    Confirm({
      pro: true,
      className: s.dialogName2,
      title: '删除角色',
      message: <div className={s.Box}>删除角色将对应删除该角色下所有数据，是否确认删除？</div>,
      onconfirm: async () => {
        console.log(e);
        const params = { user_group_ids: e };
        console.log(params);
        const res = await delRoleApi(params);
        if (res.status === 'success') {
          getData();
          Message.show({
            pro: true,
            type: 'success',
            message: '操作成功',
            showClose: false,
          });
        }
      },
    });
  };

  const disabledArr = ['审计员', '操作员', '管理员'];
  const column = [
    {
      title: '角色名',
      key: 'group',
      dataIndex: 'group',
      render: (value) => {
        return (
          <Tooltip overlay={value} placement="topLeft">
            <span>{value}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '角色说明',
      key: 'desc',
      dataIndex: 'desc',
      render: (value) => {
        return (
          <Tooltip overlay={value} placement="topLeft">
            <span>{value}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '创建时间',
      key: 'created_at',
      dataIndex: 'created_at',
      render: (value) => (value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '--'),
    },
    {
      title: '操作',
      key: 'action',
      className: s.w_6,
      render: (cur, item) => {
        const id = item.user_group_id;
        const isDisable = disabledArr.includes(item.group);
        return (
          <Dropdown
            onVisibleChange={(e) => {
              const id_ = e ? id : '';
              setIsDown(id_);
            }}
            overlay={
              <Menu>
                <>
                  <Menu.Item disabled={isDisable} onClick={() => editRoleInfo(item)}>
                    <span>编辑权限</span>
                  </Menu.Item>
                  <Menu.Item disabled={isDisable} onClick={() => delUserBtn([item.user_group_id])}>
                    <span>删除</span>
                  </Menu.Item>
                </>
              </Menu>
            }
            trigger={['click']}
          >
            <a
              className="ant-dropdown-link pr"
              onClick={(e) => {
                e.preventDefault();
              }}
            >
              管理
              <div
                className={s.jt}
                style={{ transform: id === isDown ? 'rotate(45deg)' : 'rotate(-135deg)' }}
              ></div>
            </a>
          </Dropdown>
        );
      },
    },
  ];

  useEffect(() => {}, [tableData]);
  return (
    <div className={i.mainContent}>
      <BreadCrumb
        arr={[
          { link: '', name: '角色管理' },
          { link: '', name: '角色列表', active: true },
        ]}
      />
      <div className={cn(s.content, i.p24, i.oa, i.h100p, i.mins)}>
        <div className={s.bgc}>
          <div className={s.btnBox}>
            <Button
              pro
              type="primary"
              className={s.btn}
              onClick={() => {
                setVisibleAdd(true);
              }}
            >
              添加角色
            </Button>
          </div>
          <div className={i.p24}>
            <Table columns={column} data={tableData} tableLoading={loading} loadingLabel="" />
            <div className={cn(i.df, i.aic, i.jcfe, i.pb20, i.pt20)}>
              {count > 10 && (
                <Pagination
                  total={count}
                  showQuickJumper={{ goButton: true }}
                  showSizeChanger={true}
                  pageSizeOptions={['10', '20', '50']}
                  current={query.page}
                  showTotal={(total) => `共${total}条`}
                  onChange={(page, pageSize) => {
                    setQuery({ page, pageSize });
                  }}
                />
              )}
            </div>
          </div>
        </div>
      </div>
      <Dialog
        title="添加角色"
        visible={visibleAdd}
        confirmText=""
        cancelText=""
        className={s.w540}
        onhide={() => {
          setVisibleAdd(false);
          formAdd.current.resetFields();
        }}
      >
        <div className={cn(i.p24, s.addUser)}>
          <Form
            ref={formAdd}
            {...layout}
            onValuesChange={(newItem, allValues) => {
              console.log(newItem, allValues);
              onValues2(newItem, allValues);
            }}
          >
            <Form.Item
              name="group"
              label="角色名"
              rules={[{ required: true, message: '角色名不能为空' }]}
            >
              <Input
                pro
                className={cn(i.dib, i.w300)}
                placeholder={'请输入'}
                autoComplete={'off'}
              />
            </Form.Item>

            <Form.Item
              name="desc"
              label="角色说明"
              rules={[{ required: true, message: '角色说明不能为空' }]}
            >
              <Input
                pro
                className={cn(i.dib, i.w300)}
                placeholder={'请输入'}
                autoComplete={'off'}
              />
            </Form.Item>
            <Form.Item
              name="modules"
              label="角色权限"
              rules={[{ required: true, message: '角色权限不能为空' }]}
            >
              <Select
                multiple
                allowClear
                option={roleOption}
                className={s.w_30}
                placeholder="请选择角色权限"
              />
            </Form.Item>
          </Form>
        </div>
        <div className={cn(i.tac, s.dioBtn)}>
          <Button
            className={i.vam}
            onClick={() => {
              setVisibleAdd(false);
              formAdd.current.resetFields();
            }}
          >
            取消
          </Button>
          <Button type="primary" className={cn(i.ml24, i.vam)} onClick={() => submitInfo('add')}>
            确定
          </Button>
        </div>
      </Dialog>
      <Dialog
        title={isModify ? '编辑角色' : '查看信息'}
        visible={visibleInfo}
        confirmText=""
        cancelText=""
        className={s.w540}
        onhide={() => {
          setVisibleInfo(null);
          formInfo.current.resetFields();
        }}
      >
        <div className={cn(i.p24, s.addUser)}>
          <Form
            ref={formInfo}
            {...layout}
            onValuesChange={(newItem, allValues) => {
              console.log(newItem, allValues);
              onValuesInfo(newItem, allValues);
            }}
          >
            <Form.Item
              name="group"
              label="角色名"
              rules={[{ required: true, message: '角色名不能为空' }]}
            >
              <Input
                disabled
                pro
                className={cn(i.dib, i.w300)}
                placeholder={'请输入'}
                autoComplete={'off'}
              />
            </Form.Item>

            <Form.Item
              name="desc"
              label="角色说明"
              rules={[{ required: true, message: '角色说明不能为空' }]}
            >
              <Input
                pro
                className={cn(i.dib, i.w300)}
                placeholder={'请输入'}
                autoComplete={'off'}
              />
            </Form.Item>
            <Form.Item
              name="modules"
              label="角色权限"
              rules={[{ required: true, message: '角色权限不能为空' }]}
            >
              <Select
                multiple
                allowClear
                option={roleOption}
                className={s.w_30}
                placeholder="请选择角色权限"
              />
            </Form.Item>
          </Form>
        </div>
        <div className={cn(i.tac, s.dioBtn)}>
          <Button className={i.vam} onClick={() => setVisibleInfo(null)}>
            取消
          </Button>
          <Button
            type="primary"
            className={cn(i.ml24, i.vam)}
            onClick={isModify ? () => submitInfo('info') : () => setVisibleInfo(null)}
          >
            确定
          </Button>
        </div>
      </Dialog>
    </div>
  );
}
